package cn.wolfcode.wolf2w.job;

import cn.wolfcode.wolf2w.cache.util.RedisKeys;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.vo.StrategyStatisVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

//@Component
public class RedisDataPersistenceJob {

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IUserInfoService userInfoService;

    @Scheduled(cron = "0/15 * * * * ?")
    public void startJob() {
        System.out.println("=================开始持久化==================");
        String vokey = RedisKeys.STRATEGY_STATIS_VO.join("*");
        String user_favorKey = RedisKeys.USER_FAVOR.join("*");
        Set<String> voKeys = template.keys(vokey);
        Set<String> favorKeys = template.keys(user_favorKey);
        StrategyStatisVO vo;
        Query query;
        Update update;
        for (String voKey : voKeys) {
            String vostr = template.opsForValue().get(voKey);
            vo = JSON.parseObject(vostr, StrategyStatisVO.class);
            query = new Query();
            query.addCriteria(Criteria.where("id").is(vo.getStrategyId()));
            update = new Update();
            update.set("favornum", vo.getFavornum());
            update.set("replynum", vo.getReplynum());
            update.set("thumbsupnum", vo.getThumbsupnum());
            update.set("viewnum", vo.getViewnum());
            update.set("sharenum", vo.getSharenum());
            mongoTemplate.updateMulti(query, update, Strategy.class);
        }

        for (String favorKey : favorKeys) {
            String user_favor = template.opsForValue().get(favorKey);
            String[] userfavor = favorKey.split(":");
            query = new Query();
            query.addCriteria(Criteria.where("id").is(userfavor[1]));
            update = new Update();
            update.set("favor", JSON.parseArray(user_favor, String.class));
            mongoTemplate.updateMulti(query, update, UserInfo.class);

        }

        System.out.println("=================持久化结束==================");
    }

}
